package middleware

import (
	"devOpsApi/model"
	"github.com/kataras/iris"
	"strings"
)

var PublicController = []string{"PublicController", "IndexController"}

func RBAC(ctx iris.Context) {
	//公共控制器 不进行验证
	HandlerName := strings.Split(ctx.GetCurrentRoute().MainHandlerName(), ".")

	if strings.Index(HandlerName[2], "Public") != -1 {
		ctx.Next()
		return
	}

	for _, v := range PublicController {
		if HandlerName[1] == v {
			ctx.Next()
			return
		}
	}

	//获取角色ID
	Uid := GetTokenUId(ctx)
	UserModel := model.NewUser()
	RoleId, _ := UserModel.GetUser2Role(uint(Uid))
	if RoleId == 1 {
		ctx.Next()
		return
	}

	UserInfo, _ := UserModel.GetUser(uint(Uid))
	if UserInfo.Status.Int64 != 0 {
		RBACSTOP(50008, "您处于禁用或者待审核状态", "", ctx)
		return
	}

	//根据角色ID 获取角色本身的权限路由列表
	UserRoleRouteModel := model.NewUserRoleRoute()
	RoleRoutes, _ := UserRoleRouteModel.GetAllRoutes(uint(RoleId))
	//路由列表为空 无任何权限
	if len(RoleRoutes) == 0 {
		RBACSTOP(50008, "RBAC权限验证失败，无任何权限", "", ctx)
		return
	}

	//路由对比
	flag := false
	uri := ctx.GetCurrentRoute().Name()
	for _, v := range RoleRoutes {
		if uri == v {
			flag = true
		}
	}

	if flag == false {
		RBACSTOP(50008, "RBAC权限验证失败["+uri+"]", "", ctx)
		return
	}

	ctx.Next()
	return
}

func RBACSTOP(code int, message, data string, ctx iris.Context) {
	ctx.StopExecution()
	ctx.StatusCode(iris.StatusOK)
	putData := make(map[string]interface{})
	putData["code"] = code
	putData["message"] = message
	putData["data"] = data
	_, _ = ctx.JSON(putData)
	return
}
